package com.example.lirisheng.springbootfinalexperiment.security.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class CORSFilter  implements Filter {
    protected final Logger logger = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        String []  allowDomain= {"http://localhost:63342","http://192.168.1.105:8080","http://192.168.137.1:8080","http://192.168.1.11:8080","http://47.94.215.148:8081"};
        Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
        String originHeader=((HttpServletRequest) request).getHeader("Origin");
        if(logger.isDebugEnabled()){
            logger.debug("origin:"+originHeader);
            logger.debug("allowedOrigins:"+allowedOrigins);
        }
        if (allowedOrigins.contains(originHeader)) {
            if(logger.isDebugEnabled()){
                logger.debug("entry"+"fsfsfsfsf");
            }
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            response.setHeader("Access-Control-Allow-Credentials","true");
            response.setHeader("Access-Control-Allow-Origin",originHeader);
        }

//            response.setHeader("Access-Control-Allow-Origin", "*");

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {}
}
